﻿using System;
using System.Security.Claims;
using System.Security.Principal;
using System.Web;
using System.Web.Helpers;
using System.Web.Mvc;
using System.Web.Security;
using BlankMvc.Models;
using Castle.Windsor;
using Castle.Windsor.Installer;
using Microsoft.AspNet.Identity;
using Microsoft.Owin.Security;
using MvcExtensions;
using MvcExtensions.Windsor;
using StackExchange.Profiling;

namespace BlankMvc {
	public class MvcApplication : WindsorMvcApplication {

		private WindsorContainer _windsorCntr;

		public MvcApplication() {
			log4net.Config.XmlConfigurator.Configure();
			Bootstrapper.BootstrapperTasks.Include<RegisterControllers>().Include<RegisterActionInvokers>()
				.Include<RegisterFilters>().Include<RegisterRoutes>().Include<RegisterModelBinders>()
				.Include<RegisterBundleTable>().Include<RegisterModelMetadata>();
		}

		/*protected void Application_Start() {
			AreaRegistration.RegisterAllAreas();
			FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
			RouteConfig.RegisterRoutes(RouteTable.Routes);
			BundleConfig.RegisterBundles(BundleTable.Bundles);
			ViewEngines.Engines.Clear();
			ViewEngines.Engines.Add(new RazorViewEngine());
		}*/

		protected void App_BeginRequest(object sender, EventArgs e) {
			MiniProfiler.Start();
		}

		protected void App_EndRequest(object sender, EventArgs e) {
			MiniProfiler.Stop();
		}

		protected new void Application_Start() {
			InitializeWindsor();
			base.Application_Start();
			ViewEngines.Engines.Clear();
			ViewEngines.Engines.Add(new RazorViewEngine());
		}

		protected new void Application_End() {
			base.Application_End();
			if (_windsorCntr != null)
				_windsorCntr.Dispose();
		}

		public override void Init() {
#if DEBUG
			BeginRequest += App_BeginRequest;
			EndRequest += App_EndRequest;
#endif
			PostAuthenticateRequest += MvcApplication_PostAuthenticateRequest;
			base.Init();
		}

		private void InitializeWindsor() {
			_windsorCntr = new WindsorContainer();
			_windsorCntr.Install(FromAssembly.This());
			ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory(_windsorCntr.Kernel));
		}

		static void MvcApplication_PostAuthenticateRequest(object sender, EventArgs e) {
			HttpCookie authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
			if (authCookie == null || String.IsNullOrEmpty(authCookie.Value))
				return;
			FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);
			HttpContext.Current.User = new GenericPrincipal(new UserIdentity(ticket), null);
		}
	}
}
